OpenResFile(home&"stuff.rsrc");
DefConst('kOpenSound, GetSound11Deprecated("open"));
DefConst('kCloseSound, GetSound11Deprecated("close"));
CloseResFile();

DefConst('findSymbol,
	func(targetFrame)
	begin
		foreach symbol, frame in GetRoot() do
			if frame = targetFrame and symbol <> 'currentKeyboard then
				return symbol;
		nil;
	end);

DefConst('showFunc,
	func(a)
	begin
		if GetRoot().(kAppSymbol).prefs.sounds then
			PlaySoundIrregardless(kOpenSound);
		AddDeferredSend(a, 'show, nil);
		AddDeferredSend(a, 'moveBehind, [nil]);
		local result := call kMyVerificationFunc with (nil, nil);
		if not result or result = 'unregistered then
			if (Random(1, 4) = 2) then
				GetRoot():Notify(kNotifyAlert, kAppName, kRegisterMe);

	end);

showFunc.tag := kAppSymbol;

DefConst('newDrag, 
	func(a1, a2)
	begin
		local start := ticks();
		inherited:Drag(a1, a2);
		if (Ticks() - start < 10 and self.declareSelf = 'base) then
		begin
			local myFrame := GetRoot().(kAppSymbol);
			if not myFrame.time then
			begin
				myFrame.time := Ticks();
				myFrame.target := self;
				return;
			end;
			if Ticks() - myFrame.time < GetRoot().(kAppSymbol).prefs.speed and myFrame.target = self and (call findSymbol with (self)) then
			begin
				if GetRoot().(GetUserConfig('blessedApp)) = self then
				begin
					GetRoot():Notify(kNotifyAlert, kAppName, kNoMinBackdrop);
					return;
				end;
				if GetRoot().(kAppSymbol).prefs.sounds then
					PlaySoundIrregardless(kCloseSound);
				local prefix := if GetRoot().(kAppSymbol).prefs.mark then GetRoot().(kAppSymbol).prefs.mark & " " else "";
				GetRoot().notifyIcon:AddAction(prefix & call myGetAppName with (call findSymbol with (self)), showFunc, [self]);
				call patchApp with (self);
				:Hide();
				myFrame.time := nil;
				local result := call kMyVerificationFunc with (nil, nil);
				if not result or result = 'unregistered then
					if (Random(1, 4) = 2) then
						GetRoot():Notify(kNotifyAlert, kAppName, kRegisterMe);
			end
			else
			begin
				myFrame.time := Ticks();
				myFrame.target := self
			end;
		end
	end);

DefConst('newButtonToggle,
	func()
	begin
		local list := GetRoot().notifyIcon.messageList;
		if list and Length(list) > 0 then
			foreach task in list do
				if task.fn.tag = kAppSymbol and self = task.args[0] then
				begin
					if GetRoot().(kAppSymbol).prefs.sounds then
						PlaySoundIrregardless(kOpenSound);
					GetRoot().notifyIcon:KillAction(task);
				end;
		inherited:buttonToggle();
		call patchApp with (self);
	end);